package spring.bean;


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class MyBean implements BeanNameAware,
        BeanFactoryAware, ApplicationContextAware,
        BeanPostProcessor, InitializingBean,
        DisposableBean
{
    public MyBean() {
        System.out.println("1.Bean实例化，调用构造方法");
    }



    /* Aware相关方法 */
    @Override
    public void setBeanName(String name) {
        System.out.println("2.调用BeanNameAware.setName(), 传入Bean名称：" + name);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("3. 调用 BeanFactoryAware.setBeanFactory()");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("4. 调用 ApplicationContextAware.setApplicationContext()");
    }




    public void customInitMethod() {
        System.out.println("7. 调用自定义初始化方法");
    }


    /*初始化预处理和后处理方法*/
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("【BeanPostProcessor】Before Initialization: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("【BeanPostProcessor】After Initialization: " + beanName);
        return bean;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("6. 调用 InitializingBean.afterPropertiesSet()");
    }

    /*销毁阶段*/
    @Override
    public void destroy() throws Exception {
        System.out.println("9. 调用 DisposableBean.destroy()");
    }

    public void customDestroyMethod() {
        System.out.println("10. 调用自定义销毁方法");
    }

}
